<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!doctype html>
<html>
<title>asd</title>
<!--
<meta name="viewport" content="width=device-width , initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
-->

<style type="text/css">
    .tank {
        position: fixed;
        background: url("${pageContext.request.contextPath}/static/img/b.gif");
        height: 50px;
        width: 50px;
    }

    .bullet {
        position: fixed;
        background: black;
        height: 10px;
        width: 10px;
    }
    .talk{
        height: 300px;
        width: 373px;
        left: 20px;
        bottom: 100px;
        position: fixed;
        overflow-x: hidden;
        overflow-y: scroll;
    }
</style>
<script type="text/javascript"
        src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath}/static/js/layer.js"></script>

<body
        background="${pageContext.request.contextPath}/static/img/timg.jpg"
        style="background-size: 50%;">
<div id="con"></div>
<div id="talk" class="talk"></div>
<div style="left: 20px;bottom: 20px;position: fixed;">
    <textarea rows="4" cols="50" id="msg" onfocus="inputMsg()" onblur="stopInput()" placeholder="在线聊天（最大长度50）（回车发送！）"></textarea>
</div>
<script type="text/javascript">
    var url = "ws://" + window.location.host + "${pageContext.request.contextPath}/tank?a="
    var talkUrl = "ws://" + window.location.host + "${pageContext.request.contextPath}/talk?a="
    var sock = null;
    var talkSock=null;
    var con = document.getElementById("con");
    layer.prompt({
        title: '输入昵称(最大长度5)',
        formType: 0
    }, function (text, index) {
        if(text.length>5){
            alert("昵称过长");
            return;
        }
        url = url + text;
        talkUrl = talkUrl + text;
        sock = new WebSocket(url);
        talkSock=new WebSocket(talkUrl);
        sock.onmessage = function (e) {
            console.log("message:", e.data);
            draw(e.data);
        }

        sock.onclose = function () {
            con.innerHTML = "";
            layer.prompt({
                        title: '输入昵称(最大长度5)',
                        formType: 0
                    },function(){

            });
            layer.msg("咖喱 gay gay！(刷新重玩)");
        }

        talkSock.onmessage=function(e){
            console.log("talk:", e.data);
            drawTalk(e);
        }
        document.onkeydown = keyDown;
        document.onkeyup = keyUp;
        if (window.DeviceMotionEvent) {
            window.addEventListener('deviceorientation',
                    deviceMotionHandler, false);
            window.addEventListener('touchstart', touches, false);
        }
        layer.closeAll();
    });

    var isUp = true;
    var isTalk = false;

    function keyDown(key) {
        var realkey = String.fromCharCode(key.which);
        layer.msg(realkey);
        if(isTalk)
            return;
        if (isUp) {
            keyActions(realkey, "start");
        }
        isUp = false;
    }

    function keyUp(key) {
        var realkey = String.fromCharCode(key.which);
        layer.msg("up "+realkey);
        if(key.which==13){
            if(document.getElementById("msg").value.length>50){
                layer.msg("消息最大长度 50");
                return;
            }
            if(document.getElementById("msg").value.length<=1){
                document.getElementById("msg").value=null;
                return;
            }
            talkSock.send(document.getElementById("msg").value);
            document.getElementById("msg").value=null;
        }
        keyActions(realkey, "stop");
        isUp = true;
    }

    function notDoAnything() {

    }
    var keyMoveActFun = notDoAnything;
    var keyShotActFun = notDoAnything;

    window.setInterval(function () {
        keyMoveActFun();
    }, 80);

    window.setInterval(function () {
        keyShotActFun();
    }, 300);

    function keyActions(realkey, cmd) {
        function sendKey() {
            sock.send(realkey);
        }

        if (cmd == "start") {

            if (realkey == "J") {
                keyShotActFun = sendKey;
            } else {
                keyMoveActFun = sendKey;
            }
        }

        if (cmd == "stop") {

            if (realkey == "J") {
                keyShotActFun = notDoAnything;
            } else {
                keyMoveActFun = notDoAnything;
            }
        }
    }

    function draw(data) {
        con.innerHTML = "";
        var obj = eval('(' + data + ')');
        if (obj.tank != null)
            drawTank(obj.tank);
        if (obj.bullet != null)
            drawBullet(obj.bullet);

    }

    function drawTank(tank) {
        var con = document.getElementById("con");
        for (var p in tank) {//遍历json对象的每个key/value对,p为key
            var node = document.createElement('div');
            node.setAttribute("class", "tank");
            node.setAttribute("style", "left:" + tank[p].x + "px;top:"
                    + tank[p].y + "px;")
            node.innerHTML = tank[p].name;
            con.appendChild(node);
        }
    }

    function drawBullet(bullet) {
        var con = document.getElementById("con");
        for (var p in bullet) {//遍历json对象的每个key/value对,p为key
            var node = document.createElement('div');
            node.setAttribute("class", "bullet");
            node.setAttribute("style", "left:" + bullet[p].x + "px;top:"
                    + bullet[p].y + "px;");
            con.appendChild(node);
        }
    }

    function drawTalk(e){
        var talkCon=document.getElementById("talk");
        var msg=document.createElement("h3");
        msg.setAttribute("style","color:grey;");
        msg.innerHTML= e.data;
        talkCon.appendChild(msg);
        var b=document.getElementById("talk").scrollHeight;
        document.getElementById("talk").scrollTop=b;
    }

    function deviceMotionHandler(eventData) {
        var realkey = "";
        if (sock == null)
            return;
        if (eventData.beta > 25)
            realkey = "S";
        if (eventData.beta < -10)
            realkey = "W";
        if (eventData.gamma > 20)
            realkey = "D";
        if (eventData.gamma < -20)
            realkey = "A";
        sock.send(realkey);
    }

    function touches(e) {
        //e.preventDefault();
        if (sock == null)
            return;
        sock.send("J");
    }

    function inputMsg(){
        isTalk=true;
    }

    function stopInput(){
        isTalk=false;
    }
</script>
</body>
</html>
